package com.juzhencms.apps.common.timer;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.base.busi.service.WeixinApiService;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.busi.service.AppWeixinSourceService;
import com.juzhencms.apps.busi.service.CommonService;
import com.juzhencms.apps.busi.service.DataHistoryService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class TimeTasks {
	
	@Autowired
	private WeixinApiService weixinApiService;
	
	@Autowired
	private DataHistoryService dataHistoryService;
	
	

	@Scheduled(cron = "0 */5 * * * ?") ///每隔5分钟执行一次，此定时任务准备修改后台动态可控的
	public void  sendWeiXinMessage() {
		
		//设置开发模式下不执行定时任务，避免本地执行线上的推送任务，如果需要测试，去掉这里的限制即可
		if(Config.getValue("spring.profiles.active").equals("dev")) {
			return;
		}
		log.info("sendWeiXinMessage");
    	this.weixinApiService.sendWeixinMessageScheduled();
	}
	
	@Scheduled(cron = "	0 0 9,14 * * ?")//每天下午4点提醒未处理的审批
	public void  remindWeiXinMessage() {
		
		//设置开发模式下不执行定时任务，避免本地执行线上的推送任务，如果需要测试，去掉这里的限制即可
		if(Config.getValue("spring.profiles.active").equals("dev")) {
			return;
		}
		log.info("remindWeiXinMessage");
		Date timenow=new Date();
		
		//微信通知配置
		String appid=Config.getValue("weixin.appId");
		String secret=Config.getValue("weixin.appSecret");
		String batchCheckNoticeTemplateId=Config.getValue("weixin.batchCheckNoticeTemplateId");
		if(StringUtil.isNotNullOrEmpty(batchCheckNoticeTemplateId) && StringUtil.isNotNullOrEmpty(appid) && StringUtil.isNotNullOrEmpty(secret)) {
			
			
			//查找所有待审批记录中的审批角色
			List checkRoleList=dataHistoryService.getJdbcDao().querySql("select max(id) as id,check_role_id from "+DBTable.checkRecord+" where check_status=0 group by check_role_id limit 0,2000");
			if(checkRoleList!=null && checkRoleList.size()>0) {
				String rolePregString="";
				for(int i=0;i<checkRoleList.size();i++) {
					Map tmpRole=(Map)checkRoleList.get(i);
					if(rolePregString.equals("")) {
						rolePregString+=tmpRole.get("check_role_id").toString();
					}else {
						rolePregString+="|"+tmpRole.get("check_role_id").toString();
					}
				}
				//查找这些角色对应的审批人（过滤掉没有绑定微信的用户）,排除重复用户
				List userList=dataHistoryService.getJdbcDao().querySql("select weixin_appid,weixin_openid from "+DBTable.user+" where del_flag=0 and publish=1 and weixin_appid=? and weixin_openid is not null and weixin_openid!='' and role REGEXP '(^|.*,)("+rolePregString+")(,.*|$)$'",new Object[] {appid});
				//发送微信消息通知
				
				if(userList!=null) {
					Map msgParams=new HashMap();
					msgParams.put("first", "您有未处理的审批，请尽快处理");
					//报告编号
					msgParams.put("keyword1","每天定时提醒");
					//审批事项
					msgParams.put("keyword2","有待审批的文章素材");
					//时间
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					msgParams.put("keyword3", sdf.format(timenow));
					
					
					msgParams.put("remark", "请点击查看");
					String link=null;
					try {
						String webUrl="/#/checkRecord";
						String action="/adminWeixin/login?action="+java.net.URLEncoder.encode(webUrl,"UTF-8");
						link = Config.getValue("app.adminapiDomain")+"/adminWeixin/getBaseCode?action="+ java.net.URLEncoder.encode(action,"UTF-8");
					} catch (UnsupportedEncodingException e) {
						log.error(e.getMessage(),e);
					}
					
					
					for(int i=0;i<userList.size();i++) {
						Map user=(Map)userList.get(i);
						//发送微信模板消息通知
						weixinApiService.sendTemplateMessage(appid, secret, batchCheckNoticeTemplateId, msgParams, link, user.get("weixin_openid").toString());

					}
				}
			}
			
			
			
		}
		
    	
		
		
	}
	
	
}
